<?php
/**
 * Created by PhpStorm.
 * User: zhangligang
 * Date: 17/4/24
 * Time: 上午12:01
 */

namespace App\Http\Service;


use App\Http\Models\Brand;
use App\Http\Repository\BrandRepository;
use App\Http\Repository\ProductRepository;

class ProductService extends Service
{

    /**
     * @param ProductRepository $repository
     */
    public function __construct(ProductRepository $repository)
    {
        parent::__construct($repository);

    }

    /**
     * @param string $title
     * @param int $page
     * @param int $pageSize
     * @return mixed
     */
    public function searchByTitle($title, $page, $pageSize)
    {
        $where = [
            'key' => 'title',
            'operator' => 'LIKE',
            'value' => "{$title}%"
        ];

        $offset = ($page - 1) * $pageSize;

        return $this->repository->getProductList($where, $offset, $pageSize);
    }

    /**
     * @param int $id
     * @return mixed
     */
    public function searchById($id)
    {
        return $this->repository->getProductById($id);
    }

    /**
     * @param array $params
     * @param $offset
     * @param $limit
     * @param array $columns
     * @return mixed
     */
    public function searchByParams(array $params, $offset, $limit, array $columns = ['*'])
    {

        $where = [];

        foreach ($params as $key => $param) {

            $operator = '=';

            if (in_array($key, ['title', 'short'])) $operator = 'LIKE';

            $where[] = $this->getWhereClause($key, $param, $operator);
        }

        return $this->repository->getProductList($where, $offset, $limit, $columns);

    }

    public function getBrandList(array $params, $offset, $limit, array $columns = ['*'])
    {

        $where = [];

        foreach ($params as $key => $param) {

            $operator = '=';

            $where[] = $this->getWhereClause($key, $param, $operator);
        }

        $brandRepository = new BrandRepository(new Brand());

        return $brandRepository->getBrandList($where, $offset, $limit, $columns);
    }

}